package com.codebo.yunpicturebackend.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codebo.yunpicturebackend.common.ErrorCode;
import com.codebo.yunpicturebackend.config.CosClientConfig;
import com.codebo.yunpicturebackend.exception.ThrowUtils;
import com.codebo.yunpicturebackend.manager.CosManager;
import com.codebo.yunpicturebackend.manager.FileManager;
import com.codebo.yunpicturebackend.mapper.PictureMapper;
import com.codebo.yunpicturebackend.model.dto.file.UploadPictureResult;
import com.codebo.yunpicturebackend.model.dto.picture.PictureQueryDTO;
import com.codebo.yunpicturebackend.model.dto.picture.PictureUploadDTO;
import com.codebo.yunpicturebackend.model.entity.Picture;
import com.codebo.yunpicturebackend.model.entity.User;
import com.codebo.yunpicturebackend.model.vo.PictureVO;
import com.codebo.yunpicturebackend.model.vo.UserVO;
import com.codebo.yunpicturebackend.service.PictureService;
import com.codebo.yunpicturebackend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 25912
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2025-08-13 11:40:36
 */
@Service
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
        implements PictureService
{

    @Resource
    private CosManager cosManager;

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private FileManager fileManager;
    @Resource
    private UserService userService;

    public PictureServiceImpl(CosManager cosManager)
    {
        this.cosManager = cosManager;
    }

    @Override
    public PictureVO uploadPicture(MultipartFile multipartFile, PictureUploadDTO pictureUploadDTO, User loginUser)
    {
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR, "无权限，用户拒未登录");
        Long pictureId = null;
        //1.判断是新增还是更新图片
        if (pictureUploadDTO != null)
        {
            pictureId = pictureUploadDTO.getId();
        }
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        //1.1.更新图片
        if (pictureId != null)
        {
            //校验图片是否存在
            queryWrapper.eq("id", pictureId);
            Picture picture = this.getOne(queryWrapper);
            ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
            //存在，删除原图片
            //https://yun-picture-1361877603.cos.ap-beijing.myqcloud.com/test/favicon.png
            String url = URLUtil.getPath(picture.getUrl());
            cosManager.deleteObject(url);
        }
        //1.2.新增图片
        //上传图片
        ThrowUtils.throwIf(loginUser.getId() == null, ErrorCode.PARAMS_ERROR, "用户信息错误");
        String filePath = String.format("/public/%s", loginUser.getId());
        UploadPictureResult uploadPictureResult = fileManager.uploadPicture(filePath, multipartFile);
        Picture newPicture = new Picture();
        if (pictureId != null)
        {
            newPicture.setId(pictureId);
        }
        newPicture.setUrl(cosClientConfig.getHost() + uploadPictureResult.getUrl());
        newPicture.setName(uploadPictureResult.getPicName());
        newPicture.setPicSize(uploadPictureResult.getPicSize());
        newPicture.setPicWidth(uploadPictureResult.getPicWidth());
        newPicture.setPicHeight(uploadPictureResult.getPicHeight());
        newPicture.setPicScale(uploadPictureResult.getPicScale());
        newPicture.setPicFormat(uploadPictureResult.getPicFormat());
        newPicture.setUserId(loginUser.getId());
        newPicture.setEditTime(new Date());
        this.saveOrUpdate(newPicture);
        return PictureVO.objToVO(newPicture);
    }

    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryDTO pictureQueryDTO)
    {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryDTO == null)
        {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = pictureQueryDTO.getId();
        String name = pictureQueryDTO.getName();
        String introduction = pictureQueryDTO.getIntroduction();
        String category = pictureQueryDTO.getCategory();
        List<String> tags = pictureQueryDTO.getTags();
        Long picSize = pictureQueryDTO.getPicSize();
        Integer picWidth = pictureQueryDTO.getPicWidth();
        Integer picHeight = pictureQueryDTO.getPicHeight();
        Double picScale = pictureQueryDTO.getPicScale();
        String picFormat = pictureQueryDTO.getPicFormat();
        String searchText = pictureQueryDTO.getSearchText();
        Long userId = pictureQueryDTO.getUserId();
        String sortField = pictureQueryDTO.getSortField();
        String sortOrder = pictureQueryDTO.getSortOrder();
        // 从多字段中搜索
        if (StrUtil.isNotBlank(searchText))
        {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("name", searchText)
                    .or()
                    .like("introduction", searchText)
            );
        }
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        // JSON 数组查询
        if (CollUtil.isNotEmpty(tags))
        {
            for (String tag : tags)
            {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest httpServletRequest)
    {
        PictureVO pictureVO = PictureVO.objToVO(picture);
        Long userId = picture.getUserId();
        ThrowUtils.throwIf(userId == null || userId <= 0, ErrorCode.PARAMS_ERROR, "用户id不合法");
        User user = userService.getById(userId);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        UserVO userVO = userService.getUserVO(user);
        pictureVO.setUserVO(userVO);
        return pictureVO;
    }

    /**
     * 分页获取图片封装
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request)
    {
        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollUtil.isEmpty(pictureList))
        {
            return pictureVOPage;
        }
        // 对象列表 => 封装对象列表
        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::objToVO).collect(Collectors.toList());
        // 1. 关联查询用户信息
        Set<Long> userIdSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        pictureVOList.forEach(pictureVO ->
        {
            Long userId = pictureVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId))
            {
                user = userIdUserListMap.get(userId).get(0);
            }
            pictureVO.setUserVO(userService.getUserVO(user));
        });
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }

    @Override
    public boolean deletePicture(Long id)
    {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR,"图片不存在");
        Picture picture = this.getById(id);
        cosManager.deleteObject(picture.getUrl());
        return this.removeById(id);
    }

    @Override
    public void validPicture(Picture picture)
    {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        if (StrUtil.isNotBlank(url))
        {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction))
        {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }


}




